package com.example.demo.utils;

import com.example.demo.exception.BusinessException;
import com.example.demo.task.DynamicTask;
import org.quartz.*;


/**
 * @author Administrator
 */
public class QuartzUtils {

    /**
     * 创建定时任务 定时任务创建之后默认启动状态
     *
     * @param scheduler  调度器
     */
    public static void createScheduleJob(Scheduler scheduler,String cron,String key,String desc) {
        try {
            // 构建定时任务信息 使用id作为任务唯一值，在执行时可以拿到。
            JobDetail jobDetail = JobBuilder.newJob(DynamicTask.class).withIdentity(key).withDescription(desc).build();
            // 设置定时任务执行方式
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cron);
            // 构建触发器trigger
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(key).withSchedule(scheduleBuilder).build();
            scheduler.scheduleJob(jobDetail, trigger);
        } catch (SchedulerException e) {
            throw new BusinessException("502","创建定时任务失败");
        }
    }


    /**
     * 根据任务Id暂停定时任务
     *
     * @param scheduler 调度器
     * @param jobId     定时任务名称
     */
    public static void pauseScheduleJob(Scheduler scheduler, String jobId) {
        JobKey jobKey = JobKey.jobKey(jobId);
        try {
            scheduler.pauseJob(jobKey);
        } catch (SchedulerException e) {
            throw new BusinessException("503","暂停定时任务出错");
        }
    }

    /**
     * 根据任务Id恢复定时任务
     *
     * @param scheduler 调度器
     * @param jobId     定时任务id
     */
    public static void resumeScheduleJob(Scheduler scheduler, String jobId) {
        JobKey jobKey = JobKey.jobKey(jobId);
        try {
            scheduler.resumeJob(jobKey);
        } catch (SchedulerException e) {
            throw new BusinessException("504","启动定时任务出错");
        }
    }


    /**
     * 根据任务id立即运行一次定时任务
     *
     * @param scheduler 调度器
     * @param jobId     定时任务id
     */
    public static void runOnce(Scheduler scheduler, String jobId) {
        JobKey jobKey = JobKey.jobKey(jobId);
        try {
            scheduler.triggerJob(jobKey);
        } catch (SchedulerException e) {
            throw new BusinessException("504","运行定时任务出错");
        }
    }

}
